package adapt

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"go-vue/admin/conf"
	"time"
)

const (
	JwtPreString       = "Bearer "
)

var (
	JwtSecret = []byte("this is demo")
)

type Jwt struct {
	UserId     int64
	RoleId     int64
	DepartId   int64
	permission []int
}

// CreateJwt 创建JwtToken
func CreateJwt(Id, Audience string) (string, error) {
	expiresTime := time.Now().Unix() + conf.Config.Expire
	claims := jwt.StandardClaims{
		Audience:  Audience,          // 受众
		ExpiresAt: expiresTime,       // 失效时间
		Id:        Id,                // 编号
		IssuedAt:  time.Now().Unix(), // 签发时间
		Issuer:    "system",          // 签发人
		NotBefore: time.Now().Unix(), // 生效时间
		Subject:   "system.login",    // 主题
	}
	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(JwtSecret)
	if err != nil {
		return "", err
	}
	return token, err
}

// ParseToken 解析JwtToken
func ParseToken(token string) (*jwt.StandardClaims, error) {
	jwtToken, err := jwt.ParseWithClaims(token, &jwt.StandardClaims{}, func(token *jwt.Token) (i interface{}, e error) {
		return JwtSecret, nil
	})

	//token is not valid yet 未开始生效
	if err != nil {
		return nil, err
	}

	if jwtToken == nil {
		return nil, errors.New("授权信息解析失败")
	}
	if claim, ok := jwtToken.Claims.(*jwt.StandardClaims); ok && jwtToken.Valid {
		return claim, nil
	}

	return nil, err
}
